<?php
/**
 * 文件夹体系 - 服务于工作台
 * 
 * @author Cyrano
 * @since 2019-05-17
 */

class FolderWorkbenchController extends AttachmentAdminAbstract
{
    /**
     * 新建文件夹
     */
    public function mkdir()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        /* 接收参数 */
        $pid = (int) $this->input->query('pid');
        $title = $this->input->query('title', '新建文件夹');
        $userid = (int) $this->input->query('userid', $this->_userid_fs);

        try {
            /* 检查请求方式 */
            if (! $this->input->isAJAX()) {
                throw new Zeed_Exception('请求方式错误');
            }
            
            /* 检查请求参数 */
            if (! $pid) {
                throw new Zeed_Exception('缺少参数，或参数错误');
            }
            
            /* 查询父级目录是否存在 */
            $where_parent = array('fid' => $pid, 'userid' => $userid);
            $folder_info_parent = Attachment_Model_Folder::instance()->fetchByWhere($where_parent);
            if (empty($folder_info_parent)) {
                throw new Zeed_Exception('查无此父级目录');
            }
            
            /* 创建文件夹 */
            $params_addfolder = array(
                    'parent_id' => $pid,
                    'userid' => $userid,
                    'title' => $title,
                    'sn' => '',
                    'card_id' => ''
            );
            $result = Attachment_Folder_Add::run($params_addfolder);
            if ($result['status'] != 0) {
                throw new Zeed_Exception($result['msg'], $result['status']);
            }
            $folder_info = $result['data'];
            
            /* @todo 记录日志 */
            
            
            $data['folder_info'][0] = $folder_info;
            $this->setData('data', $data);
        } catch (Zeed_Exception $e) {
            $this->setStatus($e->getCode() ? $e->getCode() : 1);
            $this->setError('创建失败 : ' . $e->getMessage());
        }
        
        return self::RS_SUCCESS;
    }
    
    /**
     * 文件夹重命名
     */
    public function rename()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        /* 接收参数 */
        $folder_id = $this->input->query('folder_id');
        $title = $this->input->query('title');
        $userid = (int) $this->input->query('userid', $this->_userid_fs);
        
        try {
            /* 检查请求方式 */
            if (! $this->input->isAJAX()) {
                throw new Zeed_Exception('请求方式错误');
            }
            
            /* 检查请求参数 */
            if (! $folder_id || ! $title) {
                throw new Zeed_Exception('缺少参数，或参数错误');
            }
            
            /* 执行更新 */
            $params_rename = array(
                    'userid' => $userid,
                    'folder_id' => $folder_id,
                    'title' => $title
            );
            $result = Attachment_Folder_Rename::run($params_rename);
            if ($result['status'] != 0) {
                throw new Zeed_Exception($result['msg'], $result['status']);
            }
            
            /* @todo 记录日志 */
            
            
        } catch (Zeed_Exception $e) {
            $this->setStatus($e->getCode() ? $e->getCode() : 1);
            $this->setError('重命名失败 : ' . $e->getMessage());
        }
        
        return self::RS_SUCCESS;
    }
    
    /**
     * 删除文件夹
     */
    public function delete()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        /* 接收参数 */
        $_id = $this->input->query('_id');

        try {
            /* 检查请求方式 */
            if (! $this->input->isAJAX()) {
                throw new Zeed_Exception('请求方式错误');
            }
            
            /* 检查请求参数 */
            if (! $_id) {
                throw new Zeed_Exception('缺少参数，或参数错误');
            }

            /* 查询文件夹信息 */
            $folder_info = Attachment_Model_Folder::instance()->fetchByPK($_id);
            if (empty($folder_info)) {
                throw new Zeed_Exception('查无此文件夹信息');
            }

            /* 校验权限归属 */
            if ($folder_info[0]['userid'] != $this->_userid) {
                throw new Zeed_Exception('不可删除他人文件夹哦');
            }
            
            /* 执行删除 */
            $params_delete = array(
                    'userid' => $folder_info[0]['userid'],
                    'folders' => $folder_info[0]['fid']
            );
            $result = Attachment_Trash::run($params_delete);
            if ($result['status'] != 0) {
                throw new Zeed_Exception($result['msg'], $result['status']);
            }
            
            /* @todo 记录日志 */
            
            
        } catch (Zeed_Exception $e) {
            $this->setStatus($e->getCode() ? $e->getCode() : 1);
            $this->setError('删除失败 : ' . $e->getMessage());
        }
        
        return self::RS_SUCCESS;
    }
    
    /**
     * 获取指定目录下的子目录及文件
     */
    public function getChildren()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        /* 接收参数 */
        $pid = (int) $this->input->query('pid');
        $t = $this->input->query('t');
        $userid = (int) $this->input->query('userid', $this->_userid_fs);
        
        try {
            /* 检查请求方式 */
            if (! $this->input->isAJAX()) {
                throw new Zeed_Exception('请求方式错误');
            }
            
            /* 检查请求参数 */
            if (! $pid) {
                throw new Zeed_Exception('缺少参数，或参数错误');
            }
            
            /* 查询父级目录是否存在 */
            $where_parent = array('fid' => $pid, 'userid' => $userid);
            $folder_info_parent = Attachment_Model_Folder::instance()->fetchByWhere($where_parent);
            if (empty($folder_info_parent)) {
                throw new Zeed_Exception('查无此父级目录');
            }
            
            /* 查询子级目录信息 */
            $where_child_folder = array(
                    'parent_id' => $pid,
                    'userid' => $userid,
                    'status' => 1
            );
            $folder_info = Attachment_Model_Folder::instance()->fetchByWhere($where_child_folder);
            
            /* 处理子级目录信息 */
            if (! empty($folder_info)) {
                foreach ($folder_info as $k => $v) {
                    /* 处理时间 */
                    $folder_info[$k]['ctime'] = Util_Timer::formatMicrotime($v['ctime'], 'Y-m-d H:i:s');
                }
            }
            
            /* 查询子级文件信息 */
            $where_child_content = array(
                    'status' => 1,
                    'mediatype' => $t,
                    'userid' => $userid,
            );
            $where_child_content['$and'] = [
                    ['pid'=>
                            ['$gt' => '0']
                    ]
            ];
            if ($folder_info_parent[0]['parent_id'] == 0) {
                $where_child_content['$and'][] = array(
                        '$or' => array(
                                array('folder_hid' => ''),
                                array('folder_hid' => $folder_info_parent[0]['hid']),
                        )
                );
            } else {
                $where_child_content['folder_hid'] = $folder_info_parent[0]['hid'];
            }
            $order_child_content = array('ctime' => 'DESC');
            
            $content_info = Attachment_Model_Content::instance()->fetchByWhere($where_child_content, $order_child_content);
            
            /* 处理子级文件信息 */
            if (! empty($content_info)) {
                $card_id_temp_arr = array();
                foreach ($content_info as $k => &$v) {
                    /* 处理容量 */
                    $v['filesize_format'] = Util_File::formatFilesize($v['filesize']);
                    
                    /* 处理扩展信息 */
                    $v['extra'] = $v['extra'] ? json_decode($v['extra'], true) : array();
                    
                    /* 处理时间 */
                    $v['ctime'] = Util_Timer::formatMicrotime($v['ctime'], 'Y-m-d H:i:s');
                    
                    /* 获取原文件信息 */
                    $v['title_from'] = $v['title'];
                    $file_from_info = Attachment_Model_Content::instance()->fetchByPK($v['pid']);
                    if (! empty($file_from_info)) {
                        $v['wb_type'] = $file_from_info[0]['mediatype'];
                        $v['title_from'] = $file_from_info[0]['title'];
                    }
                    
                    /* 获取原文件隶属行动信息 */
                    if (isset($card_id_temp_arr[$v['pid']])) {
                        $v['card_id'] = $card_id_temp_arr[$v['pid']]['_id'];
                        $v['card_title'] = $card_id_temp_arr[$v['pid']]['title'];
                        $v['sn'] = $card_id_temp_arr[$v['pid']]['sn'];
                    } else {
                        $key = $v['pid'];
                        if ($v['wb_type'] == 'video') {
                            $where_card = array('attachments_video' => new MongoRegex("/$key/i"));
                        } elseif ($v['wb_type'] == 'audio') {
                            $where_card = array('attachments_audio' => new MongoRegex("/$key/i"));
                        } else {
                            $where_card = array('attachments_img' => new MongoRegex("/$key/i"));
                        }
                        $card_info = Archive_Model_Card::instance()->fetchByWhere($where_card);
                        if (! empty($card_info)) {
                            $v['card_id'] = $card_info[0]['_id'];
                            $v['card_title'] = $card_info[0]['title'];
                            $v['sn'] = $card_info[0]['sn'];
                            $card_id_temp_arr[$v['pid']] = array(
                                    '_id' => $card_info[0]['_id'],
                                    'title' => $card_info[0]['title'],
                                    'sn' => $card_info[0]['sn']
                            );
                        }
                    }
                    
                    /* 获取原文件隶属案件信息 */
                    $v['archive_title'] = '';
                    $archive_info = Archive_Model_Content::instance()->fetchByFV('sn', $v['sn']);
                    if (! empty($archive_info)) {
                        $v['archive_title'] = $archive_info[0]['title'];
                    }
                }
            }
            
            $data = array(
                    'folder_info_parent' => $folder_info_parent[0],
                    'folder_info' => $folder_info,
                    'content_info' => $content_info
            );
            $this->setData('data', $data);
        } catch (Zeed_Exception $e) {
            $this->setStatus($e->getCode() ? $e->getCode() : 1);
            $this->setError('查询失败 : ' . $e->getMessage());
        }
        
        return self::RS_SUCCESS;
    }
    
    /**
     * 获取指定目录下的所有子级目录
     */
    public function getFoldersForSelect()
    {
        $this->addResult(self::RS_SUCCESS, 'json');
        
        /* 接收参数 */
        $folder_hid = $this->input->query('folder_hid');
        $userid = (int) $this->input->query('userid', '');
        
        try {
            /* 检查请求方式 */
            if (! $this->input->isAJAX()) {
                throw new Zeed_Exception('请求方式错误');
            }
            
            /* 检查请求参数 */
            if (! $folder_hid) {
                throw new Zeed_Exception('缺少参数，或参数错误');
            }
            
            /* 处理目录节点 */
            $hid_top = substr($folder_hid, 0, 7);
            
            /* 执行查询 */
            $data['folders_forselect'] = Attachment_Model_Folder::instance()->getAllFoldersForSelect($hid_top, null, $userid);
            
            $this->setData('data', $data);
        } catch (Zeed_Exception $e) {
            $this->setStatus($e->getCode() ? $e->getCode() : 1);
            $this->setError('查询失败 : ' . $e->getMessage());
        }
        
        return self::RS_SUCCESS;
    }
}

// End ^ LF ^ encoding
